﻿using Biletomaty.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Device.Location;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace Biletomaty.ViewModels
{
    public class BiletomatViewModel : INotifyPropertyChanged
    {
        public bool IsDataLoaded = false;
        public EventHandler<LocationEventArgs> MainMap_SetItems;
        private ObservableCollection<BiletomatModel> _biletomaty = new ObservableCollection<BiletomatModel>();
        
        public ObservableCollection<BiletomatModel> Biletomaty
        {
            get 
            { 
                return _biletomaty;  
            }
            set
            {
                if (value != null)
                {
                    _biletomaty = value;
                    NotifyPropertyChanged("Biletomaty");
                }
            }
        }



        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        internal void LoadData()
        {
            var client = new WebClient();

            client.OpenReadCompleted += (s, e) =>
                {
                    var bil = new ObservableCollection<BiletomatModel>();
                    using (var stream = e.Result)
                    {
                        var rootSer = new DataContractJsonSerializer(typeof(RootObject));
                        var rootObject = (RootObject)rootSer.ReadObject(stream);
                        foreach (var result in rootObject.features)
                        {
                            bil.Add(new BiletomatModel()
                            {
                                ID = result.id,
                                Title = result.properties.opis,
                                Description = result.properties.opis_long,
                                Location = new GeoCoordinate(result.geometry.coordinates[0], result.geometry.coordinates[1]) 
                            });
                        }
                    }
                    Biletomaty = bil;
                    IsDataLoaded = true;
                    if (MainMap_SetItems != null && Biletomaty.Count > 0)
                        MainMap_SetItems(this, new LocationEventArgs(Biletomaty));
                };

            client.OpenReadAsync(new Uri("http://www.poznan.pl/featureserver/featureserver.cgi/biletomaty_wgs/"));
        }
    }
}
